package org.example.threadobjectclasscommonmethods;

/**
 * @description: 线程控制单双数打印
 * @author: MoodAir
 * @Date: 2020/5/10 0010 21:56
 */
public class WaitNotifyPrintOddEvenSyn {

  /**
   * 创建静态锁
   */
  private static final Object lock = 1;
  /**
   * 统计字段
   */
  private static int count = 1;

  /**
   * @Author: MoodAir
   * @Description: main方法创建两个线程启动，循环打印单双
   * @Date: 2020/5/10 0010 21:58
   * @param: args
   * @return: void
   * @Version: 1.0
   */
  public static void main(String[] args) {
    /*
       新建两个线程
       第一个是处理奇数.第二个是处理偶数(用唯一运算)
       用Synchronized来通讯
     */
    new Thread(() -> {
      while (count < 100) {
        synchronized (lock) {
          if ((count & 1) == 0) {
            System.out.println(Thread.currentThread().getName() + ":" + count++);
          }
        }
      }
    }, "偶数线程").start();

    new Thread(() -> {
      while (count < 100) {
        synchronized (lock) {
          if ((count & 1) == 1) {
            System.out.println(Thread.currentThread().getName() + ":" + count++);
          }
        }
      }
    }, "奇数线程").start();
  }
}
